<template>
  <div class="baseList">
    <div class="head">
      <NavBar
        @goBack="goBack"
        :title="title"
      ></NavBar>
      <div class="searchFun">
        <div class="searchField">
          <van-field
            v-model="searchValue"
            type="text"
            placeholder="Input Name,Phone number,Address or Label"
            :left-icon="iconSearch"
            @click-left-icon="search"
          />
        </div>
      </div>
    </div>
    <div class="list">
      <van-pull-refresh
        v-model="refreshing"
        @refresh="onRefresh"
      >
        <van-list
          v-model="loading"
          :finished="finished"
          finished-text="没有更多了"
          @load="onLoad"
        >
          <div
            class="item"
            v-for="(item, index) in list"
            :key="index"
          >
            <div
              class="base"
              @click="backJump(item)"
            >
              <span class="name">{{ item.name }}</span>
              <span class="phone">{{ item.phone }}</span>
              <van-button
                v-if="item.location"
                type="primary"
                size="mini"
              >{{ item.location }}</van-button>
            </div>

            <van-cell
              @click="backJump(item)"
              class="body"
              :value=item.detailInfo
            />
            <div class="menuArr">
              <div
                @click="edit(item)"
                class="edit"
              ></div>
              <div
                @click="deleteItem(item)"
                class="deleteItem"
              ></div>
            </div>
          </div>
        </van-list>
      </van-pull-refresh>
    </div>
    <div class="bottom">
      <van-button
        @click="addNewAddress"
        type="primary"
        size="large"
      >Add Address</van-button>
    </div>
    <deletePop
      :show="show"
      @closePop="closePop"
      @confirmDelete=confirmDelete
    ></deletePop>
  </div>
</template>
<script>
import NavBar from '@/components/NavBar'
import deletePop from '@/components/pop/deletePop.vue'
import { Consumer, validata } from '@/model/consumer.js'
import { Saddress, validatas } from '@/model/selectAddress.js'
import { getAddressList, deleteAddress } from 'api/user.js'
import { Toast } from 'vant'
export default {
  name: 'baseList',
  components: {
    NavBar,
    deletePop
  },
  created() {
    /**
     *  id
     *  1 : 表示consignor
     *  2 : 表示receiver
     */

    if (this.$route.params.id == undefined) {
      this.$router.go(-1)
    } else {
      this.who = this.$route.params.who
    }
  },
  mounted() {
    // this.$store.dispatch('setConsignorClick', true)
    // this.$store.dispatch('setReceiverClick', true)
  },
  data() {
    return {
      show: false,
      title: 'Address book',
      iconSearch: require('assets/image/icon_search.png'),
      searchValue: '',
      list: [],
      loading: false,
      finished: false,
      refreshing: false,
      item: '', //当前选中要删除的 选项
      who: ''
    }
  },
  methods: {
    backJump(item) {
      // alert("backJump")
      // alert(this.who)
      const {
        name,
        phone,
        address,
        provinceId,
        cityId,
        zoneId,
        consumerId,
        addressId,
        type,
        location,
        provinceName,
        cityName,
        zoneName
      } = item
      let city=provinceName + '  ' + cityName + '  ' + zoneName
      const str = JSON.stringify({
        name,
        phone,
        address,
        provinceId,
        cityId,
        zoneId,
        city,
        consumerId,
        addressId,
        type,
        location,
        provinceName,
        cityName,
        zoneName
      })
      if (this.who == 'ConsignorInfo') {
        this.$store.dispatch('setConsignorInfo', str)
      } else if (this.who == 'ReceiverInfo') {
        this.$store.dispatch('setReceiverInfo', str)
      }
      setTimeout(() => {
        this.$router.replace({
          path: '/main'
        })
      }, 200)
    },
    confirmDelete() {
      this.show = false
      const { addressId } = JSON.parse(this.item)

      let { phone } = JSON.parse(this.$store.state.app.userInfo)
      let selectAddress = new Saddress(addressId, phone)
      // console.log(selectAddress)

      if (validatas(selectAddress, Saddress)) {
        let data = selectAddress._getData()
        deleteAddress(data)
          .then(res => {
            Toast.success({
              message: res.message
            })
            setTimeout(() => {
              this.goBack()
            }, 1000)
          })
          .catch(err => {
            Toast.fail({
              message: err
            })
          })
      }
    },
    closePop() {
      this.show = false
    },
    goBack() {
      this.$router.replace({
        path: '/main'
      })
    },
    addNewAddress() {
      this.$router.push({
        name: 'editItem',
        params: {
          id: 3,
          who: this.who
        }
      })
    },
    getList() {
      let { phone, consumerId } = JSON.parse(this.$store.state.app.userInfo)
      // console.log('vuex', this.$store.state.app.userInfo)
      // let token = this.$store.state.app.token
      let consumer = new Consumer(consumerId, phone, this.searchValue)
      console.log(consumer)
      if (validata(consumer, Consumer)) {
        // console.log('yes')
        let data = consumer._getData()
        // console.log(data)
        getAddressList(data)
          .then(res => {
            // console.log(res.data.result)
            let data = res.data.result
            data.forEach(item => {
              item.detailInfo = item.provinceName + ' ' + item.cityName + ' ' + item.zoneName + ' ' + item.address

              if (item.type == null) {
                item.location = false
              } else if (item.type == 1) {
                item.location = '家'
              } else if (item.type == 2) {
                item.location = '公司'
              } else {
                item.location = '学校'
              }
            })

            this.list = data
          })
          .catch(err => {
            Toast.fail({
              message: err
            })
          })
      }
    },
    search() {
      // alert('搜索')
      this.getList()
    },
    edit(item) {
      //   alert('编辑')
      const {
        name,
        phone,
        address,
        provinceId,
        cityId,
        zoneId,
        consumerId,
        addressId,
        type,
        location,
        provinceName,
        cityName,
        zoneName
      } = item
      const str = JSON.stringify({
        name,
        phone,
        address,
        provinceId,
        cityId,
        zoneId,
        consumerId,
        addressId,
        type,
        location,
        provinceName,
        cityName,
        zoneName
      })
      this.$router.push({
        // path: '/editItem'
        name: 'editItem',
        params: { id: 2, str, who: this.who }
      })
    },
    deleteItem(item) {
      this.item = JSON.stringify(item)
      this.show = true
    },
    onLoad() {
      //检测 滑动到里底部 就会触发 onLoad 事件 只有将finished  改为 true 不再 触发 onLoad事件
      setTimeout(() => {
        // alert('6')
        if (this.refreshing) {
          this.list = []
          this.refreshing = false
        }

        this.getList()

        // this.loading = false
        this.finished = true
        if (this.list.length >= 10) {
          //当接口 无结果集的时候 改成 true  不再触发 load 事件
          this.finished = true
        }
      }, 1000)
    },
    onRefresh() {
      // 清空列表数据
      this.finished = false

      // 重新加载数据
      // 将 loading 设置为 true，表示处于加载状态
      this.loading = true
      this.onLoad()
    }
  }
}
</script>
<style lang="scss" scoped>
@import './baseList.scss';
</style>
